package com.ckjava.test.gencode.web;

import com.ckjava.test.gencode.component.GenCom;
import com.ckjava.test.gencode.component.TemplateCom;
import com.ckjava.test.gencode.entity.GenInfo;
import com.ckjava.test.gencode.entity.GenScheme;
import com.ckjava.test.gencode.entity.GenTable;
import com.ckjava.test.gencode.entity.GenTemplate;
import com.ckjava.test.gencode.service.GenCodeService;
import com.ckjava.xutils.Constants;
import com.ckjava.xutils.FileUtils;
import com.ckjava.xutils.http.HttpResponse;
import io.swagger.annotations.Api;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

@Api
@RequestMapping("/api/gencode")
@RestController
public class GencodeController {

	@Autowired
	private GenCodeService genCodeService;
	@Autowired
	private TemplateCom templateCom;
	@Autowired
	private GenCom genCom;
	
	@GetMapping
	public HttpResponse<String> doGen(@ModelAttribute GenInfo genInfo) throws Exception {

		File entityFilePath = new File("E:\\genCode\\entity");
		File mapperFilePath = new File("E:\\genCode\\mapper");

		GenTable genTable = new GenTable();
		genTable.setName(genInfo.getTableName());
		genTable = genCodeService.getTableFormDb(genTable);

		genTable.setClassName(genInfo.getClassName());

		GenScheme genScheme = new GenScheme();
		genScheme.setGenTable(genTable);
		genScheme.setPackageName(genInfo.getPackageName());
		genScheme.setModuleName(genInfo.getModuleName());
		genScheme.setSubModuleName(genInfo.getSubModuleName());

		genScheme.setFunctionName(genInfo.getFunctionName());
		genScheme.setFunctionAuthor(genInfo.getAuthorName());

		GenTemplate entityTemplate = GenCom.fileToObject("MyBatisEntity.xml", GenTemplate.class);
		String entityData = templateCom.renderString(entityTemplate.getContent(), genCom.getDataModel(genScheme));

		String entityFile = entityFilePath.getAbsolutePath().concat("\\").concat(genInfo.getClassName()+".java");
		FileUtils.writeStringToFile(new File(entityFile), entityData, false, Constants.CHARSET.UTF8);

		GenTemplate genTemplate = GenCom.fileToObject("mapper.xml", GenTemplate.class);
		String data = templateCom.renderString(genTemplate.getContent(), genCom.getDataModel(genScheme));

		String mapperFile = mapperFilePath.getAbsolutePath().concat("\\").concat(genInfo.getClassName()+"Mapper.xml");
		FileUtils.writeStringToFile(new File(mapperFile), data, false, Constants.CHARSET.UTF8);

		return HttpResponse.getReturn(null, Constants.HTTPCODE.code_200, null);
	}
}
